#include "FileMd5.h"

FileMd5::FileMd5(QObject *parent) : QObject(parent)
{

}
////////////////////slot
void FileMd5::checkDuplicate(const QString &path)
{
    QHash<QByteArray,QStringList> res;
    QStringList files = getFiles(path);
    for(int i = 0;i<files.count();++i)
    {
        QString filename = files.at(i);
        QByteArray md5 = getFileMd5(filename);
        res[md5].append(filename);
        emit progress(i+1,files.count());
    }

    emit gotDuplicate(res);
}

/////////////////func
QStringList FileMd5::getFiles(const QString &path)
{
    QStringList res;
    QDir dir(path);
    QFileInfoList infolist = dir.entryInfoList(QDir::Files |
                                               QDir::Dirs |
                                               QDir::NoDotAndDotDot);
    for(int i = 0;i<infolist.count();++i)
    {
        QFileInfo info = infolist.at(i);
        if(info.isDir())
        {
            QString subDir = info.absoluteFilePath();
            QStringList files = getFiles(subDir);
            res.append(files);
        }
        else
        {
            QString filename = info.absoluteFilePath();
            res.append(filename);
        }
    }
    return res;
}

QByteArray FileMd5::getFileMd5(const QString &filename)
{
    QFile file(filename);
    if(file.open(QIODevice::ReadOnly))
    {
        QCryptographicHash hash(QCryptographicHash::Md5);
        while(!file.atEnd())
        {
            QByteArray content = file.read(100 * 1024 * 1024);
            hash.addData(content);
        }
        QByteArray md5 = hash.result().toHex();
        file.close();
        return md5;
    }
    return QByteArray();
}
